<template>
    <el-dialog class="ba-operate-dialog" :model-value="baTable.form.operate=='deliver' ? true : false" @close="baTable.toggleForm">
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">发货</div>
        </template>

        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <el-form
                v-if="!baTable.form.loading"
                ref="formRef"
                :model="baTable.form.extend?.info"
            >

                <el-row style="margin-top: 20px" v-for="(item,index) in (baTable.form.extend?.info?.express_data || [])" >
                    <el-col :span="8">
                        <FormItem
                            label="快递公司"
                            type="remoteSelect"
                            v-model="item.express_code"
                            :input-attr="{
                                    pk: 'xxz_express.code',
                                    field: 'name',
                                    remoteUrl: '/admin/express/getExpress',
                                }"
                        />
                    </el-col>
                    <el-col :span="10">
                        <FormItem style="margin-left: 30px" :label="t('order.express_no')" type="string" v-model="item.express_no" prop="express_no" :placeholder="t('Please input field', { field: t('order.express_no') })" />
                    </el-col>
                </el-row>

                <!-- POS机机身号输入区域 - 只有当订单包含POS机商品时才显示 -->
                <div v-if="hasPosGoods" style="margin-top: 20px;">
                    <el-divider content-position="left">POS机机身号</el-divider>
                    
                    <el-alert 
                        type="info" 
                        show-icon 
                        :closable="false"
                        style="margin-bottom: 20px;"
                    >
                        <p>请输入POS机机身号，激活码将由立刷系统自动生成。</p>
                    </el-alert>
                    
                    <el-row v-for="(activation, index) in posActivations" :key="index" style="margin-bottom: 15px;">
                        <el-col :span="12">
                            <el-input 
                                v-model="activation.device_sn" 
                                placeholder="请输入POS机机身号"
                                clearable
                            />
                        </el-col>
                        <el-col :span="4" style="margin-left: 10px;">
                            <el-button 
                                type="danger" 
                                :icon="Delete" 
                                circle 
                                size="small"
                                @click="removePosActivation(index)"
                                v-if="posActivations.length > 1"
                            />
                        </el-col>
                    </el-row>
                    
                    <el-row style="margin-top: 10px;">
                        <el-col :span="12">
                            <el-button @click="addPosActivation" type="primary" size="small">
                                添加POS机
                            </el-button>
                        </el-col>
                    </el-row>
                </div>

<!--                <el-row style="margin-top: 10px"  >-->
<!--                    <el-col :span="8">-->

<!--                        <el-button @click="add" >添加快递</el-button>-->

<!--                    </el-col>-->
<!--                    <el-col :span="10">-->

<!--                    </el-col>-->
<!--                    <el-col :span="3">-->

<!--                    </el-col>-->
<!--                </el-row>-->

<!--                <el-alert style="margin-top: 20px"  type="info" show-icon :closable="false">
                    <p>确认全部完成后订单将转为已发货状态</p>
                </el-alert>

                <FormItem style="margin-top: 20px" label="是否全部完成" type="switch" v-model="send_status" />-->

            </el-form>

        </el-scrollbar>

        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="onDeliver(formRef)" type="primary">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {inject, ref, watch, computed} from 'vue'
import { useI18n } from 'vue-i18n'
import type BaTable from '/@/utils/baTable'
import { timeFormat } from '/@/utils/common'
import { isEmpty } from 'lodash-es'
import {ElMessage, ElMessageBox, FormInstance} from "element-plus";

import FormItem from '/@/components/formItem/index.vue'
import createAxios from "/@/utils/axios";
import {
    Delete,
} from '@element-plus/icons-vue'

const formRef = ref<FormInstance>()
const baTable = inject('baTable') as BaTable

const { t } = useI18n()

const send_status = ref(1);

// POS机激活码相关
const posActivations = ref<any[]>([])

// 检查订单中是否有POS机商品
const hasPosGoods = computed(() => {
    if (!baTable.form.extend?.info?.goods) {
        return false
    }
    return baTable.form.extend.info.goods.some((item: any) => item.is_pos == 1 || item.is_pos === true)
})

// 初始化POS机机身号
const initPosActivations = () => {
    posActivations.value = []
    // 默认添加一个空的POS机机身号输入框
    posActivations.value.push({
        device_sn: '',
        order_id: baTable.form.extend?.info?.id || 0
    })
}

// 监听弹窗打开
watch(() => baTable.form.operate, (newVal) => {
    if (newVal === 'deliver') {
        // 始终初始化POS机激活码，让hasPosGoods计算属性来决定是否显示
        initPosActivations()
    }
})
const onDeliver = (formRef: any) => {
    const submitData: any = {
        datas: baTable.form.extend?.info?.express_data,
        id: baTable.form.extend?.info?.id,
        send_status: send_status.value
    }
    
    // 只有当订单包含POS机商品时才添加POS机激活码数据
    if (hasPosGoods.value) {
        // 过滤掉空的机身号
        const validPosActivations = posActivations.value.filter(item => item.device_sn && item.device_sn.trim() !== '')
        submitData.pos_activations = validPosActivations
    }

    createAxios({
        url: '/admin/order/deliver',
        method: 'post',
        data: submitData
    },{
        loading:true
    },{
        text: '提交中...'
    })
        .then((res) => {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            baTable.onTableHeaderAction('refresh', {})
            baTable.form.operate = '';
        })
        .catch((resx) => {
        })
}



/**
 * 追加元素
 */
const add = () => {
    const new_arr  = {
        "express_code":"",
        "express_no":"",
    };
    baTable.form.extend?.info?.express_data?.push(new_arr);
}

const del = (index: number) => {

    if (index >= 0 && index < (baTable.form.extend?.info?.express_data?.length || 0)) {
        baTable.form.extend?.info?.express_data?.splice(index,1)
    }
}

// 添加POS机机身号输入框
const addPosActivation = () => {
    posActivations.value.push({
        device_sn: '',
        order_id: baTable.form.extend?.info?.id || 0
    })
}

// 删除POS机机身号输入框
const removePosActivation = (index: number) => {
    if (posActivations.value.length > 1) {
        posActivations.value.splice(index, 1)
    }
}
</script>

<style scoped lang="scss">
:deep(.color-red) {
    color: var(--el-color-danger) !important;
}
.table-el-tree {
    :deep(.el-tree-node) {
        white-space: unset;
    }
    :deep(.el-tree-node__content) {
        display: block;
        align-items: unset;
        height: unset;
    }
}

.titles{
    display: flex;
    text-align: center;
    font-weight: 900;
    color: var(--el-text-color-regular);
    height: 35px;
    align-items: center;
    justify-content: center;
}
</style>
